package com.lgcns.android2;

import java.util.ArrayList;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;

public class ProfileListActivity extends ListActivity implements OnClickListener{

	private ProfileListAdapter mListAdapter;
	private LoadProfileTask mLoadProfileTask;
	private ArrayList<Integer> mIndexer;
	private QuickAction mQuickAction;
	
	private static final String[] PROJECTION = { Constants._ID,
			Constants.ID_NUM, Constants.TITLE_CODE, Constants.TITLE, Constants.NAME, Constants.TEL,
			Constants.EMAIL, Constants.LOCATION, Constants.JOB, Constants.PHOTO, Constants.MANAGER };
	
	private static final String[] TITLE_MAP= {"팀장", "부장", "차장", "과장", "대리", "사원", "(신입)사원" };
	
	private final ActionItem callAction = new ActionItem();
	private final ActionItem smsAction = new ActionItem();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Setup ListAdapter
		mListAdapter = new ProfileListAdapter(this);
		setListAdapter(mListAdapter);

		//Retrieve Database
		mLoadProfileTask = new LoadProfileTask();
		mLoadProfileTask.execute();
		
		//Setting QucikAction
		callAction.setId(R.id.callPopup);
		smsAction.setId(R.id.smsPopup);
		callAction.setTitle("Call");
		smsAction.setTitle("Send SMS");
		callAction.setIcon(getResources().getDrawable(R.drawable.ic_dialer));
		smsAction.setIcon(getResources().getDrawable(R.drawable.ic_messages));
		callAction.setOnClickListener(this);
		smsAction.setOnClickListener(this);
	}
	
	

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
	    MenuItem item = menu.add(0,1,0,"여러명에게 SMS 보내기");
	    item.setIcon(R.drawable.ic_messages);
	    item.setAlphabeticShortcut('a');
	    return true;


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case 1:
                //SMS보내기 구현
                return true;
        }
        return false;

    }

    /**
	 * List에서 선택된 멤버의 정보를 들고 ProfilePopupActivity로 화면 전환.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		ProfileViewHolder holder = (ProfileViewHolder) v.getTag();
		Intent intent = new Intent(this, ProfilePopupActivity.class);
		intent.putExtra(Constants.ID_NUM, holder.idNum);
		intent.putExtra(Constants.NAME, holder.name);
		intent.putExtra(Constants.TITLE, holder.title);
		intent.putExtra(Constants.TEL, holder.tel);
		intent.putExtra(Constants.EMAIL, holder.email);
		intent.putExtra(Constants.LOCATION, holder.location);
		intent.putExtra(Constants.JOB, holder.job);
		startActivity(intent);
	}
	
	/**
	 * Profile List를 구성하기 위한 Adapter. Adapter에서 사용되는 Cursor는 LoadProfileTask에서
	 * 생성되어 처리된다.
	 * @author yoon.joohyun
	 */
	/* package */class ProfileListAdapter extends CursorAdapter {

		private Context mContext;
		private LayoutInflater mInflater;
		private BitmapFactory.Options options = new BitmapFactory.Options();

		public ProfileListAdapter(Context context) {
			super(context, null, true);
			this.mContext = context;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			options.inSampleSize = 4;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if(!getCursor().moveToPosition(position))
                throw new IllegalStateException((new StringBuilder()).append("couldn't move cursor to position ").append(position).toString());
            
            if (convertView == null || convertView.getTag() == null) {
                v = newView(mContext, getCursor(), parent);
            } else {
                v = convertView;
            }
            bindView(v, mContext, getCursor());
            //Index header 추가(직급)
            bindSectionHeader(v, position, getCursor().getInt(getCursor().getColumnIndex(Constants.TITLE_CODE)));
            return v;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			
			//get information from cursor
		    int idNum = cursor.getInt(cursor.getColumnIndex(Constants.ID_NUM));
			String name = cursor.getString(cursor.getColumnIndex(Constants.NAME));
			String title = cursor.getString(cursor.getColumnIndex(Constants.TITLE));
			String tel = cursor.getString(cursor.getColumnIndex(Constants.TEL));
			String email = cursor.getString(cursor.getColumnIndex(Constants.EMAIL));
			String location = cursor.getString(cursor.getColumnIndex(Constants.LOCATION));
			String job = cursor.getString(cursor.getColumnIndex(Constants.JOB));
			String manager = cursor.getString(cursor.getColumnIndex(Constants.MANAGER));

			//Store information in ViewHolder
			ProfileViewHolder holder = (ProfileViewHolder) view.getTag();
            if (holder == null) 
            {
                holder = new ProfileViewHolder();
                view.setTag(holder);
            }

            holder.idNum = idNum;
            holder.name = name;
            holder.title = title;
            holder.tel = tel;
            holder.email = email;
            holder.location = location;
            holder.job = job;
            holder.manager = manager;

            Bitmap bm = Util.getProfileImage(context, cursor, options);

			//Setting image
			QuickContactBadge imgProfile = (QuickContactBadge) view.findViewById(R.id.imgProfile);
			imgProfile.setImageBitmap(bm);
			imgProfile.setTag(tel);

			//Setting name + title 
			TextView nameProfile = (TextView) view.findViewById(R.id.nameProfile);
			nameProfile.setText(new StringBuffer(name).append(" ").append(title));
			
			//Setting Manager
			TextView managerProfile = (TextView) view.findViewById(R.id.manager);
			if(manager != null) {
				managerProfile.setVisibility(View.VISIBLE);
				managerProfile.setText(manager);
			} else {
				managerProfile.setVisibility(View.GONE);
			}
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View v = mInflater.inflate(R.layout.profile_list_item, parent, false);
			QuickContactBadge imgProfile = (QuickContactBadge) v.findViewById(R.id.imgProfile);
			imgProfile.setOnClickListener(ProfileListActivity.this);
			return v;
		}
		
        private void bindSectionHeader(View itemView, int position, int title_code) {
        
        	LinearLayout headerLayout = (LinearLayout)itemView.findViewById(R.id.listHeader);
        	
        	if (mIndexer.contains(position)) {
        		headerLayout.setVisibility(View.VISIBLE);
        		
        		TextView textHeader = (TextView)itemView.findViewById(R.id.textHeader);
        		textHeader.setText(TITLE_MAP[title_code]);
        	} else {
        		headerLayout.setVisibility(View.GONE);
        	}
        }
	}

	/**
	 * Profile을 조회하는 thread로 Profile 조회 후 결과 값(cursor)을 ListAdapter에 넣어준다.
	 * @author yoon.joohyun
	 */
	private class LoadProfileTask extends AsyncTask<Void, Void, Cursor> {

		/*
		 * Profile List 조회
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Cursor doInBackground(Void... params) {
			Cursor cursor = ProfileListActivity.this.managedQuery(
			        ProfileProvider.PROFILES_CONTENT_URI, PROJECTION, null, null,
					new StringBuffer(Constants.TITLE_CODE).append(", ").append(
							Constants.NAME).toString());
			return cursor;
		}

		/*
		 * doInBackground() 결과 값으로 받은 Cursor을 ListAdapter에 적용한다.
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Cursor cursor) {
			if (cursor == null || cursor.isClosed()) {
				return;
			}
			updateSectionIndexer(cursor);
			ProfileListActivity.this.mListAdapter.changeCursor(cursor);
		}
		
		//Cursor loop을 돌면서 Index(직급)을 표시해야 될 Row position을 기억
		private void updateSectionIndexer(Cursor cursor) {
			mIndexer = new ArrayList<Integer>();
			int previousTitleCode = -1;
			cursor.moveToPosition(-1);
			while (cursor.moveToNext()) {
				int titleCode = cursor.getInt(cursor.getColumnIndex(Constants.TITLE_CODE));
				if(previousTitleCode != titleCode) {
					mIndexer.add(cursor.getPosition());
					previousTitleCode = titleCode;
				}
			}
		}
	}
	
	/**
	 * Profile information 보관 저장소 
	 * @author yoon.joohyun
	 */
	class ProfileViewHolder {
	    public int idNum;
		public String name;
		public String title;
		public String tel;
		public String email;
		public String location;
		public String job;
		public String manager;
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.imgProfile:
			mQuickAction = new QuickAction(v);
			mQuickAction.addActionItem(callAction);
			mQuickAction.addActionItem(smsAction);
			mQuickAction.show();
			break;
		case R.id.callPopup:
			startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + (String)mQuickAction.getParentView().getTag())));
			mQuickAction.dismiss();
			break;
		case R.id.smsPopup:
			startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + (String)mQuickAction.getParentView().getTag())));
			mQuickAction.dismiss();
			break;
		}
	}
}
